package com.ruoyi.framework.config;

import me.chanjar.weixin.common.service.WxOAuth2Service;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.api.impl.WxMpOAuth2ServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpUserServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@ConditionalOnClass(WxMpService.class)
public class WxMpServiceConfig {

    @Resource
    private WxProperties properties;

    @Bean
    public WxMpDefaultConfigImpl wxMpDefaultConfigImpl() {
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(properties.getAppId()); // 设置微信公众号的appid
        config.setSecret(properties.getMpSecret()); // 设置微信公众号的app corpSecret
        config.setToken(properties.getToken()); // 设置微信公众号的token
        config.setAesKey(properties.getAesKey()); // 设置微信公众号的EncodingAESKey
        return config;
    }

    @Bean
    @ConditionalOnMissingBean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpDefaultConfigImpl());
        return wxMpService;
    }

    @Bean
    @ConditionalOnMissingBean
    public WxMpUserService wxMpUserService() {
        return new WxMpUserServiceImpl(this.wxMpService());
    }

    @Bean
    @ConditionalOnMissingBean
    public WxOAuth2Service wxOAuth2Service() {
        return new WxMpOAuth2ServiceImpl(this.wxMpService());
    }

}
